package com.tanami.rynmar;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import android.util.Log;

public class PriceListDownloadTask extends AsyncTask<URI, Integer, ByteArrayOutputStream> {
    
	private WeakReference<RynmarActivity> mParentActivity = null;
	private	InputStream				  mPriceListXml = null; 

	public PriceListDownloadTask(RynmarActivity parentActivity) {
		mPriceListXml = parentActivity.getResources().openRawResource(R.raw.cennik);
        mParentActivity = new WeakReference<RynmarActivity>(parentActivity);
    }
	
	/*
	 * doInBackground
	 * 
	 * */
	protected ByteArrayOutputStream doInBackground(URI... uri) {    	
		//InputStream is = getResources().openRawResource(R.raw.cennik);
		InputStream is = mPriceListXml;
		ByteArrayOutputStream inputStream = new ByteArrayOutputStream();
		try
		{
        	HttpClient client = new DefaultHttpClient();
	        HttpGet request = new HttpGet();
	        request.setURI(uri[0]);
	        HttpResponse response = client.execute(request);
	        
	        int statusCode = response.getStatusLine().getStatusCode();
	        if( statusCode < 300 )
	        	is = response.getEntity().getContent();
	        
	        int thisLine;
			try {
				
				while ((thisLine = is.read()) != -1) {
					inputStream.write(thisLine);
				}
				inputStream.flush();
				
				if (inputStream != null){
					inputStream.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        
	        client.getConnectionManager().shutdown();
		}catch(Exception e)
		{
			Log.e("Download xml", "general exception", e);
		}
    	return inputStream;
    }

	/*
	 * onPostExecute
	 * */
    protected void onPostExecute(ByteArrayOutputStream data) {
    	// now we do something that requires the context
        if (mParentActivity.get() != null) {
            // the WeakReference is still valid and hasn't been reclaimed
            // by the GC
            final RynmarActivity parentActivity = mParentActivity.get();
            parentActivity.OnDownloadComplete(data);
        }
    }
}
